
const GAMENAMES="gameNames";
const GAMEURLS = "gameUrls";
const GAMENOTWORK = "gameNotWork";
const GAMEREDIRECT = "gameRedirect";
let reqListener= (event)=>{
    console.log(event.type)
}
let checkUrl = (url,callback)=>{
    let xhr = new XMLHttpRequest();

    xhr.addEventListener('error',e=>{
        callback&&callback({err:e.type})
    });
    xhr.addEventListener('readystatechange',(e)=>{
        let xhr = e.target;
        if(xhr.readyState == xhr.HEADERS_RECEIVED) {
            var code = xhr.getResponseHeader("status");
            console.log(url,code,xhr.status)    
            callback&&callback({data:xhr.status});
            
        }
    })
    xhr.open('GET',url);
    xhr.send();
}

// 检查游戏地址
let checkGameUrls = ()=>{
    let checkCount = 0,gamesNotWork = [];
    let games = localStorage.getItem(GAMEURLS);
    if(games){
        let gamesArr = JSON.parse(games);

        gamesArr.forEach(game=>{
            let url = game.url;
            checkUrl(url,(res)=>{   
                if(res.err){
                    console.log('请求出错',res.err);
                    game.code = res.err;
                    gamesNotWork.push(game)
                }else if(res.data!=200){
                    console.log(`header code:${res.data}`)
                    game.code = res.data;
                    gamesNotWork.push(game)
                }
                console.log(`已经检查${checkCount}次，总数${gamesArr.length}`)
                if(++checkCount>gamesArr.length-5){   // 等所有请求执行完一次存入
                    console.log(`执行完毕，有问题的游戏数量为${gamesNotWork.length}`)
                    localStorage.setItem(GAMENOTWORK,JSON.stringify(gamesNotWork));
                }
            })
        })
    }
}
// checkGameUrls();

// checkUrl(url)
let get = (url,callback)=>{
    let xhr = new XMLHttpRequest();
    xhr.addEventListener('error',(e)=>{
        callback&&callback({err:e})
    })
    xhr.addEventListener('load',(e)=>{
        var response = xhr.response;
        callback&&callback({data:response});
    })
    xhr.open('GET',url);
    xhr.send();
}

let startCount = 72,count=24;
let namesArr = [];
/**
 * 检索所有游戏名称
 */
let retrieveGameNames = ()=>{
    let url = `https://51h5.online/api/v1/games/more/undefined/${startCount}-${startCount+count}`;
    console.log("开始搜索url:",url)
    get(url,(res)=>{
        let reg = /game\/([^"]+)"/g
        let arr,key = GAMENAMES;
        let names = [];
        while (arr = reg.exec(res.data)) {  
            console.log('game name:',arr[1])          
            names.push(arr[1]);
        }
        namesArr = namesArr.concat(names);
        if(names.length==24){
            startCount+=count;
            retrieveGameNames();
        }else{
            localStorage.setItem(key,namesArr); // 直到最后一页写入数据
        }
    })
}
// retrieveGameNames();
/**
 * 检索游戏页地址
 */
let retrieveGameUrls = ()=>{
    let gameNames = localStorage.getItem(GAMENAMES).split(',');
    let arr = [],key = GAMEURLS;
    let reqCount = 0,gameUrlsArr = [];
    let retrieveGameUrl = (name)=>{
        const url = `https://51h5.online/play/${name}`;
        get(url,(res)=>{
            reqCount++;
            if(res.err){    //发生错误
                console.log('获取url失败',err)
                return;
            }
            let reg = /\+'([^']+)'\+`"><\/iframe>`/;
            const html = res.data;

            if(arr = html.match(reg)){
                console.log(`发现链接：${name}:${arr[1]}`);
                gameUrlsArr.push({
                    name: name,
                    url: arr[1]
                });
                if(reqCount == gameNames.length){
                    localStorage.setItem(key,JSON.stringify(gameUrlsArr));
                    console.log('已经存储好gameUrls');
                }
                
            };
        })
    }
    gameNames.forEach((value)=>{
        retrieveGameUrl(value);
    });
}
// retrieveGameUrls();
/**
 * 检查游戏是否自动跳转
 */
let checkGameRedirect = ()=>{
    let gameNames = localStorage.getItem(GAMENAMES).split(',');
    let openNewTab = (url,onRemoving)=>{
        chrome.tabs.create({url:url,active:false},tab=>{
            console.log('打开新标签页',tab)
            setTimeout(() => {
                chrome.tabs.remove(tab.id,()=>{
                    console.log('移除tab成功')
                    onRemoving()
                })
            }, 10*1000);
        })
    }
    let tabLoop = index=>{
        if(index<gameNames.length){
            const name = gameNames[index];
            const url = `https://51h5.online/play/${name}`;
            openNewTab(url,()=>{
                tabLoop(++index)
            });
        }
        
    };


    tabLoop(0);

    chrome.runtime.onMessage.addListener((message,sender)=>{
        console.log('接收到消息',message);
        const arr = JSON.parse(localStorage.getItem(GAMEREDIRECT))||[];
        if(Object.keys(message).length){
           arr.push(message);
           localStorage.setItem(GAMEREDIRECT,JSON.stringify(arr));
        }
    })

}



window.utils =  {
    retrieveGameNames:retrieveGameNames,
    retrieveGameUrls: retrieveGameUrls,
    checkGameUrls:checkGameUrls,
    checkGameRedirect:checkGameRedirect,
}
